package config

import (
	"log"
	"os"

	"github.com/joho/godotenv"
)

type Config struct {
	AppPort            string
	MysqlDSN           string
	JwtSecret          string
	OssEndpoint        string
	OssAccessKeyID     string
	OssAccessKeySecret string
	OssBucketName      string

	WechatAppId     string
	WechatAppSecret string

	EsUrl              string
	EsChatMessageIndex string

	UploadRoot string
}

var Conf *Config

func Init() {
	err := godotenv.Load()
	if err != nil {
		log.Println("No .env file found, reading config from environment variables")
	}

	Conf = &Config{
		AppPort:            getEnv("APP_PORT", "8080"),
		MysqlDSN:           getEnv("MYSQL_DSN", ""),
		JwtSecret:          getEnv("JWT_SECRET", "secret"),
		OssEndpoint:        getEnv("OSS_ENDPOINT", ""),
		OssAccessKeyID:     getEnv("OSS_ACCESS_KEY_ID", ""),
		OssAccessKeySecret: getEnv("OSS_ACCESS_KEY_SECRET", ""),
		OssBucketName:      getEnv("OSS_BUCKET_NAME", ""),

		WechatAppId:     getEnv("WECHAT_APP_ID", ""),
		WechatAppSecret: getEnv("WECHAT_APP_SECRET", ""),

		EsUrl:              getEnv("ES_URL", ""),
		EsChatMessageIndex: getEnv("ES_CHAT_MESSAGE_INDEX", ""),

		UploadRoot: getEnv("UPLOAD_ROOT", ""),
	}
}

func getEnv(key, fallback string) string {
	if value, ok := os.LookupEnv(key); ok {
		return value
	}
	return fallback
}
